package com.blb.blb_erp.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.blb_erp.entity.SMenu;
import com.blb.blb_erp.entity.SRole;
import com.blb.blb_erp.entity.SUser;
import com.blb.blb_erp.mapper.SMenuMapper;
import com.blb.blb_erp.mapper.SRoleMapper;
import com.blb.blb_erp.mapper.SUserMapper;
import com.blb.blb_erp.service.ISMenuService;
import com.blb.blb_erp.service.ISRoleService;
import com.blb.blb_erp.service.ISUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户Realm
 */
public class UserRealm extends AuthorizingRealm {

//    @Autowired
//    private ISUserService userService;
//    @Autowired
//    private ISMenuService menuService;
//    @Autowired
//    private ISRoleService roleService;
    @Autowired
    private SUserMapper userMapper;
    @Autowired
    private SRoleMapper roleMapper;
    @Autowired
    private SMenuMapper menuMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获得用户对象
        SUser user = (SUser) principalCollection.getPrimaryPrincipal();
        //查询权限和角色
        List<SMenu> menus = menuMapper.selectMenusByUserId(user.getId());
        List<SRole> roles = roleMapper.selectRolesByUserId(user.getId());
        //保存权限和角色名称的集合
        List<String> strRoles = new ArrayList<>();
        roles.forEach(r -> strRoles.add(r.getRoleName()));
        List<String> strMenus = new ArrayList<>();
        menus.forEach(m -> strMenus.add(m.getMenuName()));
        //返回带有角色和权限名称的授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(strRoles);
        info.addStringPermissions(strMenus);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获得账号
        String username = authenticationToken.getPrincipal().toString();
        //通过账号查询用户
        SUser user = userMapper.selectUserByUsername(username);
        if(user == null){
            throw new UnknownAccountException("此用户不存在");
        }
        //返回验证信息  参数：1、用户对象 2、正确密码 3、盐 4、realm名称
        return new SimpleAuthenticationInfo(user,user.getPassWord(), ByteSource.Util.bytes(user.getSalt()),getName());
    }
}
